package edu.sctu.treebuilder.day02;

/**
 * Created by apple on 05/02/2018.
 */
public class StateController {

    private State state = State.DATA;
    private CharacterReader reader;

    private boolean isEmitPending = false;

    private Token emitPending;

    Token.Tag tagPending;
    Token.StartTag startPending = new Token.StartTag();
    Token.EndTag endPending = new Token.EndTag();


    public StateController(CharacterReader reader) {
        this.reader = reader;
    }

    public Token read() {

        // 不同的从输入流中读取字符，进入状态机进行处理。
        // 当遇到结束标记时，跳出循环。
        // isEmitPending为结束标记，字符进入状态机后会经过不同状态的处理，如果某一个状态已经识别到分词，则将该标记设为 True。
        while (!isEmitPending) {

            state.read(this, reader);

        }

        isEmitPending = false;

        return emitPending;

    }

    public void transition(State newState) {
        this.state = newState;
    }

    public void advanceTransition(State newState) {
        reader.advance();
        transition(newState);
    }

    public void emit(Token token) {

        emitPending = token;
        isEmitPending = true;

    }

    public Token.Tag createTagPending(boolean start) {

        tagPending = start ? startPending.reset() : endPending.reset();

        return tagPending;
    }

    public void emitTagPending() {

        emit(tagPending);
    }

    public void emit(String data) {

        emitPending = new Token.Character(data);
        isEmitPending = true;
    }
}
